﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using MedReg.Classes;

namespace MedReg.Utils
{
    internal class ImportXML
    {
        public XmlNodeEventHandler xdoc_UnknownNode { get; set; }

        public XmlAttributeEventHandler serializer_UnknownAttribute { get; set; }

        public void ImportFile(string fn)
        {
            var files = from line in File.ReadAllLines(fn)
                        where (line.Contains("xmlns=\"StuffEntry\">") | line.Contains("xmlns=\"Employee\">"))
                        select new {File = fn, Line = line};
                        


            /*
            var canwork = false;
            try
            {
                canwork = (files.Count() > 0 & files.First());
            }
            catch (Exception)
            {

                canwork = false;
            }
            
            if (!canwork)
            {
                return;
            }
            */
            foreach (var file in files)
            {
                var fs = new FileStream(file.File, FileMode.Open);

                //if (file.Line.Contains("xmlns=\"StuffEntry\">"))
                //{
                //    ImportStaff(fs);
                //}
                if (file.Line.Contains("xmlns=\"Employee\">"))
                {
                    ImportEmployee(fs);
                }
            }
           
        }
        private void ImportEmployee (FileStream fs)
        {
            fs.Position = 0;

            var xdoc = new XmlSerializer(typeof(ArrayOfEmployee));

            //xdoc.UnknownNode += new XmlNodeEventHandler(xdoc_UnknownNode);
            //xdoc.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);
            var EmployeeCol = new ArrayOfEmployee();
            try
            {
                EmployeeCol = (ArrayOfEmployee)xdoc.Deserialize(fs);
            }
            catch (Exception)
            {
                Logger.WriteLine("Поврежденный файл!!!");
                fs.Close();
                return;
            }
            

            Logger.WriteLine("Прочитан массив сотрудников " + EmployeeCol.Count + " элементов");
            
            var sEmpl = new Employee();
            sEmpl.ImportList(EmployeeCol);
            fs.Close();
        }
        private void ImportStaff(FileStream fs)
        {
            fs.Position = 0;

            var xdoc = new XmlSerializer(typeof(ArrayOfStaffEnrty));

            //xdoc.UnknownNode += new XmlNodeEventHandler(xdoc_UnknownNode);
            //xdoc.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);

            var StaffEntryCol = (ArrayOfStaffEnrty)xdoc.Deserialize(fs);

            Logger.WriteLine("Прочитан массив штатного расписания " + StaffEntryCol.Count + " элементов");

            Console.WriteLine(StaffEntryCol.Count);
            var sSt = new StaffEntry();
            sSt.ImportList(StaffEntryCol);
            fs.Close();
        }

        public void ImportDir(string startdir, BackgroundWorker worker, DoWorkEventArgs e)
        {
            Logger.WriteLine("Сканирую директорию ...");
            try
            {
                var files = from file in Directory.EnumerateFiles(startdir,
                                "*.xml", SearchOption.AllDirectories)
                            select new
                            {
                                File = file
                                
                            };

                Logger.WriteLine("Найдено похожих на реестр XML фалов - " + files.Count());
                //Progress.SetProgressMax(files.Count());
                int i = 1;
                var j = files.Count();
                foreach (var f in files)
                {
                    var percentComplete = (int)(((double)i/(double)j)*100);
                    worker.ReportProgress(percentComplete);
                    i++;
                    Logger.WriteLine("Обрабатка ...");
                    Logger.WriteLine(f.File.ToString());
                    ImportFile(f.File.ToString());
                    
                }
                
            }
            catch (UnauthorizedAccessException UAEx)
            {
                Logger.WriteLine(UAEx.Message);
            }
            catch (PathTooLongException PathEx)
            {
                Logger.WriteLine(PathEx.Message);
            }
        }

    }
}